using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Services.FileSystem;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI.WebControls;

namespace Code5Systems.FormMaster.Business
{
	
	public partial class FormController
	{
		public void CreateFormRwd(int moduleId, Control phForm, bool isEditMode)
		{
			FormInfo objFormInfo = default(FormInfo);
			FormSettings objFormSettings = default(FormSettings);
			HtmlGenericControl oMainDiv = new HtmlGenericControl("div");
			HtmlGenericControl oFormDiv = new HtmlGenericControl("div");

			HtmlGenericControl oRowFluid = default(HtmlGenericControl);
			Panel oOutsideDiv = new Panel();
			oOutsideDiv.Attributes.Add("class", "C5SLLC_control-group");
			HtmlGenericControl oControlDiv = default(HtmlGenericControl);

			byte iCols = default(byte);
			byte iRows = default(byte);
			CellInfo[,] tAry = new CellInfo[2, 2];
			CellInfo oCellInfo = null;
			string C5LLC_controls_Classes = "C5LLC_controls";
			
			FormCreationSetup();
			
			//Get the Module Settings
			objFormSettings = Utility.GetFormSettings(moduleId);

			if (objFormSettings.UseDefaultFieldFormatting)
			{
				C5LLC_controls_Classes += " C5SLLC_FormItem";
			}
			
			//Get the FormInfo Object
			objFormInfo = _formInfo;
			
			//_validationGroup = (string) (Guid.NewGuid().ToString());

			string mainDivStyle = String.Empty;
			oMainDiv.ID = "C5SLLC_MainFormTable" + FormInfo.CurrentPage.PageNum.ToString();
			if (!String.IsNullOrWhiteSpace(this._formSettings.TableClass))
			{
				oMainDiv.Attributes.Add("class", String.Format("{0} c5sFormMain", this._formSettings.TableClass));
			}
			else
			{
				oMainDiv.Attributes.Add("class", "c5sFormMain");
			}

			if (!String.IsNullOrWhiteSpace(objFormSettings.FormTableWidth))
			{
				if (objFormSettings.FormTableWidth.Contains("%"))
				{
					mainDivStyle += String.Format("width:{0};", objFormSettings.FormTableWidth);
				}
				else
				{
					mainDivStyle += String.Format("width:{0}px;", objFormSettings.FormTableWidth);
				}
			}

			if (!String.IsNullOrWhiteSpace(mainDivStyle))
			{
				oMainDiv.Attributes.Add("style", mainDivStyle);
			}

			string mainDivClass = String.Empty;
			if (objFormSettings.FormTableAlignment != HorizontalAlign.NotSet)
			{
				switch(objFormSettings.FormTableAlignment)
				{
					case HorizontalAlign.Center:
						mainDivClass += "C5SLLC_width C5SLLC_center";
						break;
					case HorizontalAlign.Left:
						mainDivClass += "C5SLLC_width C5SLLC_left";
						break;
					case HorizontalAlign.Right:
						mainDivClass += "C5SLLC_width C5SLLC_right";
						break;
				}
			}

			if (!string.IsNullOrEmpty(objFormSettings.TableClass))
			{
				mainDivClass += String.Format("{0};", objFormSettings.TableClass);
			}

			if (String.IsNullOrWhiteSpace(mainDivClass))
			{
				oMainDiv.Attributes.Add("class", mainDivClass);
			}

			if (!string.IsNullOrEmpty(objFormInfo.TableClass))
			{
				oFormDiv.Attributes.Add("class", objFormInfo.TableClass);
			}

			oRowFluid = new HtmlGenericControl("div");
			oRowFluid.Attributes.Add("class", "C5LLC_row-fluid");
			oControlDiv = new HtmlGenericControl("div");
			oControlDiv.ID = "tdFormMasterHeaderCell" + FormInfo.CurrentPage.PageNum.ToString();
			oRowFluid.Controls.Add(oControlDiv);
			oMainDiv.Controls.Add(oRowFluid);

			string cellClasses = String.Empty;

			oFormDiv.ID = (string) (Utility.GetValidControlID(objFormInfo.FormName) + FormInfo.CurrentPage.PageNum.ToString());
			if (this._formInfo.CurrentPage.TableColumns > 1)
			{
				oFormDiv.Attributes.Add("class", "C5LLC_form-horizontal");
			}
			
			//tAry a two dimensional Array representing Columns x Rows Matrix
			//We will keep information about what is going on in each location
			//usung CellInfo class
			tAry = GetTableMatrix(objFormInfo, objFormInfo.CurrentPage.PageNum);
			
			if (_saveSerializationFixups)
			{
				_saveSerializationFixups = false;
				DoLegacySerializationFixup();
			}

			for (iRows = 1; iRows <= objFormInfo.CurrentPage.TableRows; iRows++)
			{
				if (iRows == 1)
				{
					oRowFluid = new HtmlGenericControl("div");
					oRowFluid.Attributes.Add("class", "C5LLC_row-fluid C5LLC_controls-row");
					oFormDiv.Controls.Add(oRowFluid);
				}
				else if (objFormSettings.HardRowBreaks)
				{
					oRowFluid = new HtmlGenericControl("div");
					oRowFluid.Attributes.Add("class", "C5LLC_row-fluid C5LLC_controls-row");
					oFormDiv.Controls.Add(oRowFluid);
				}
				
				for (iCols = 1; iCols <= objFormInfo.CurrentPage.TableColumns; iCols++)
				{
					try
					{
						if (!(tAry[iRows - 1, iCols - 1] == null))
						{
							oCellInfo = tAry[iRows - 1, iCols - 1];
						}
					}
					catch (Exception)
					{
						//Do Noting
					}

					if (oCellInfo.FormControlInfo == null)
					{
						continue;
					}

					if (this.Pages.Count > 1 && oCellInfo.FormControlInfo.Type == ControlType.SubmitButton)
					{
						continue;
					}
					
					if (!oCellInfo.IsSpanned)
					{
						oOutsideDiv = new Panel();

						oOutsideDiv.Attributes.Add("class", String.Format("C5LLC_control-group {0}", cellClasses));
						if (oCellInfo.FormControlInfo.ShowOnOwnRow)
						{
							oOutsideDiv.Attributes.Add("style", String.Format("min-height:{0}px;width:100%;", objFormSettings.CellHeight));
						}
						else
						{
							oOutsideDiv.Attributes.Add("style", String.Format("min-height:{0}px;width:{1}px;", objFormSettings.CellHeight, objFormSettings.GroupWidth));
						}
						oControlDiv = new HtmlGenericControl("div");
						oControlDiv.Attributes.Add("class", C5LLC_controls_Classes);
						
						//If this is a Label or Submit Button Colspan gets weird
						//If the Control Lables are set to "2" on the Left
						//Then if the Control Lable is Hidden the ColSpan simply doubles
						//Else the ColSpan doubles minus 1 for the Control Label

						AddCellControlsRwd(oCellInfo.FormControlInfo, oOutsideDiv, oControlDiv, iRows.ToString(), iCols.ToString(), moduleId, phForm);
						if (oCellInfo.FormControlInfo.Type != ControlType.HiddenField)
						{
							oRowFluid.Controls.Add(oOutsideDiv);
						}
						
						// Get the Cascading script for this control
						if (!oCellInfo.IsEmpty)
						{
							if (oCellInfo.FormControlInfo.IsParentList || oCellInfo.FormControlInfo.IsChildList)
							{
								GetCascadedControlScript(objFormInfo.CurrentPage.PageNum, oCellInfo.FormControlInfo);
							}
						}
					}
				}
			}
			
			if (objFormInfo.ShowCcMe && (!isEditMode) && (objFormInfo.CurrentPage.PageNum == Pages.Count))
			{
				oRowFluid = new HtmlGenericControl("div");
				oRowFluid.Attributes.Add("class", "C5LLC_row-fluid");
				oRowFluid.ID = "trC5SCCMe";

				oOutsideDiv = new Panel();
				oOutsideDiv.Attributes.Add("class", String.Format("C5LLC_control-group {0}", cellClasses));
				oOutsideDiv.Attributes.Add("style", "float:none;text-align:center;padding-bottom:5px;");
				oControlDiv = new HtmlGenericControl("div");
				oControlDiv.Attributes.Add("class", C5LLC_controls_Classes);

				var chkCCMe = new CheckBox();
				chkCCMe.ID = "chkCcMe";
				chkCCMe.CssClass = "SubHead";
				chkCCMe.Attributes.Add("style", "display:inline-block;");
				chkCCMe.Text = Localization.GetString("ControlCcMe", this._sharedResourceFile);
				oControlDiv.Controls.Add(chkCCMe);
				oOutsideDiv.Controls.Add(oControlDiv);
				
				oRowFluid.Controls.Add(oOutsideDiv);
				oFormDiv.Controls.Add(oRowFluid);
			}
			
			if (!isEditMode)
			{
				if (objFormInfo.UseCaptcha)
				{
					//if (Pages.Count >= 1 && objFormInfo.CurrentPage.PageNum == Pages.Count)
					//{
					//	oRowFluid = new HtmlGenericControl("div");
					//	oRowFluid.Attributes.Add("class", "C5LLC_row-fluid");
					//	oRowFluid.ID = "trC5SCaptcha";
						
					//	oControlDiv = new HtmlGenericControl("div");
					//	oControlDiv.Attributes.Add("class", "C5LLC_controls C5SCaptchaCell");
					//	oControlDiv.ID = "tdC5SCaptcha";

					//	oRowFluid.Controls.Add(oControlDiv);
					//	oFormDiv.Controls.Add(oRowFluid);
					//}
					switch (objFormSettings.CaptchaType)
					{
						case CaptchaType.DefaultCaptcha:
							if (Pages.Count >= 1 && objFormInfo.CurrentPage.PageNum == Pages.Count)
							{
								oRowFluid = new HtmlGenericControl("div");
								oRowFluid.Attributes.Add("class", "C5LLC_row-fluid");
								oRowFluid.ID = "trC5SCaptcha";

								oControlDiv = new HtmlGenericControl("div");
								oControlDiv.Attributes.Add("class", "C5LLC_controls C5SCaptchaCell");
								oControlDiv.ID = "tdC5SCaptcha";

								oRowFluid.Controls.Add(oControlDiv);
								oFormDiv.Controls.Add(oRowFluid);
							}
							break;
						case CaptchaType.GoogleReCaptcha:
							if (Pages.Count >= 1 && objFormInfo.CurrentPage.PageNum == Pages.Count)
							{
								oRowFluid = new HtmlGenericControl("div");
								oRowFluid.Attributes.Add("class", "C5LLC_row-fluid");
								oRowFluid.ID = "trC5SCaptcha";

								oControlDiv = new HtmlGenericControl("div");
								oControlDiv.Attributes.Add("class", "g-recaptcha C5SreCaptchaCell");
								oControlDiv.Attributes.Add("data-sitekey", objFormSettings.SiteKey);

								oRowFluid.Controls.Add(oControlDiv);
								oFormDiv.Controls.Add(oRowFluid);
							}
							break;
						default:
							break;
					}
				}
			}
			
			if (_hasRequredFieldValidators)
			{
				if (objFormSettings.UseValidationSummary)
				{
					oRowFluid = new HtmlGenericControl("div");
					oRowFluid.Attributes.Add("class", "C5LLC_row-fluid");
					oRowFluid.ID = "trC5SValSmry" + FormInfo.CurrentPage.PageNum.ToString();

					ValidationSummary oValSummary = new ValidationSummary();
					oValSummary.ID = "c5svalsmry" + Utility.GetValidControlID((string)(DateTime.Now.ToString("s") + FormInfo.CurrentPage.PageNum.ToString()));
					oValSummary.ValidationGroup = objFormInfo.ValidationGroup;
					oValSummary.ShowMessageBox = objFormSettings.ShowValidationSummaryMessageBox;
					oValSummary.ShowSummary = objFormSettings.ShowValidationSummary;

					oValSummary.DisplayMode = objFormSettings.ValidationSummaryMode;
					oValSummary.CssClass = objFormSettings.ValidationSummaryCssClass;
					oValSummary.HeaderText = objFormSettings.ValidationSummaryHeading;

					oControlDiv = new HtmlGenericControl("div");
					oControlDiv.Attributes.Add("class", C5LLC_controls_Classes);
					oControlDiv.ID = "tdC5SValSmry" + FormInfo.CurrentPage.PageNum.ToString();
					
					oControlDiv.Controls.Add(oValSummary);
					oRowFluid.Controls.Add(oControlDiv);

					oFormDiv.Controls.AddAt(0, oRowFluid);
				}
			}
			if (Pages.Count >= 1 && objFormInfo.CurrentPage.PageNum == Pages.Count)
			{
				oRowFluid = new HtmlGenericControl("div");
				oRowFluid.Attributes.Add("class", "C5LLC_row-fluid");
				oRowFluid.ID = "trDefaultSubmitButton" + FormInfo.CurrentPage.PageNum.ToString();
				oRowFluid.Visible = false;

				oControlDiv = new HtmlGenericControl("div");
				oControlDiv.Attributes.Add("class", "C5LLC_controls C5LLC_button-cell");
				oControlDiv.ID = "tdDefaultSubmitButton" + FormInfo.CurrentPage.PageNum.ToString();

				if (this.FormButtons.Count > 0)
				{
					var button = this.FormButtons.Last();
					if (button != null)
					{
						var parent = button.Parent;
						parent.Controls.Remove(button);
						oControlDiv.Controls.Add(button);
						Utility.RemoveControlRecursive(parent);
						oRowFluid.Visible = true;
					}
				}

				oRowFluid.Controls.Add(oControlDiv);

				oFormDiv.Controls.Add(oRowFluid);
			}

			if (_hasRequredFieldValidators && !objFormSettings.SuppressReqFldText)
			{
				oRowFluid = new HtmlGenericControl("div");
				oRowFluid.Attributes.Add("class", "C5LLC_row-fluid");
				oRowFluid.ID = "trC5SSuppressReqFldText" + FormInfo.CurrentPage.PageNum.ToString();

				oControlDiv = new HtmlGenericControl("div");
				oControlDiv.Attributes.Add("class", "C5LLC_controls C5LLC_ReqFldText");
				oControlDiv.ID = "tdC5SSuppressReqFldText" + FormInfo.CurrentPage.PageNum.ToString();

				Label oLabel = new Label();
				oLabel.ID = "lblRequired" + FormInfo.CurrentPage.PageNum.ToString();
				oLabel.CssClass = "Normal";
				oLabel.Text = objFormSettings.RequiredFieldSymbol + Localization.GetString("Required.Text", this._sharedResourceFile);

				oControlDiv.Controls.Add(oLabel);
				oRowFluid.Controls.Add(oControlDiv);

				oFormDiv.Controls.Add(oRowFluid);
			}

			oMainDiv.Controls.Add(oFormDiv);

			phForm.Controls.Add(oMainDiv);

			HtmlInputHidden hdnDisabledValidators = new HtmlInputHidden();
			hdnDisabledValidators.ID = Constants.DISABLED__VALIDATORS_ID;
			if (this.Pages.Count() == 1)
			{
				System.Collections.Generic.List<string> listValID = new System.Collections.Generic.List<string>();
				foreach (BaseValidator item in _disabledValidators)
				{
					listValID.Add(item.ClientID);
				}

				hdnDisabledValidators.Value = (string)(listValID.ToCsv());
				phForm.Controls.Add(hdnDisabledValidators);
			}

			if (FormInfo.CurrentPage.PageNum == this.Pages.Count())
			{
				//if (objFormInfo.UseCaptcha)
				//{
				//	this.GetCaptchaControlScript(phForm);
				//}
				if (objFormInfo.UseCaptcha)
				{
					switch (objFormSettings.CaptchaType)
					{
						case CaptchaType.DefaultCaptcha:
							this.GetCaptchaControlScript(phForm);
							break;
						case CaptchaType.GoogleReCaptcha:
							this.GetReCaptchaControlScript(phForm);
							break;
						default:
							break;
					}
				}

				if (this.Pages.Count() > 1)
				{
					this.GetWizardScripts(phForm);
				}
				
				GetFieldRuleScripts(phForm, hdnDisabledValidators);

				GeneratePageScripts(phForm, _pageScripts, isEditMode, DotNetNuke.Framework.AJAX.IsEnabled());
			}
		}
		
		//Add the control to the Design Time Form with the Error Message for any Validators
		private Panel AddCellControlsRwd(FormControlInfo objFormControlInfo, Panel oOutsideDiv, HtmlGenericControl controlDiv, string row, string col, int moduleId, Control phForm)
		{
			FormControlInfo objValidatorFormControlInfo = default(FormControlInfo);
			Label oLabelControl = (Label) null;
			WebControl oInputControl = default(WebControl);
			BaseValidator oValidatorControl = default(BaseValidator);
			Literal oLiteral = null;
			//Panel oOutsideDiv = new Panel();
			HtmlGenericControl oInputDiv = new HtmlGenericControl("div");
			HtmlGenericControl oInputValSpan = new HtmlGenericControl("span");
			string strControlClass = default(string);
			string strTdClass = string.Empty;
			string labelStyle = String.Empty;
			FormFieldRulesInfo fieldRule = default(FormFieldRulesInfo);
			FieldRulesScriptInfo oFieldRulesScriptInfo = null;
			bool enableValidators = true;
			
			string strFieldOnEventText = string.Empty;
			
			FormSettings objFormSettings = Utility.GetFormSettings(moduleId);
			
			if (objFormControlInfo != null)
			{
				List<FieldRulesScriptInfo> sInfos = default(List<FieldRulesScriptInfo>);
				sInfos = GetAllFieldRuleScriptInfoByTarget(objFormControlInfo.ID);
				
				//Create the Outer Div Element. Panel renders as a Div
				oOutsideDiv.ID = objFormControlInfo.ID + "div";

				if (this._formInfo.CurrentPage.LabelPosition == 2)
				{
					oInputValSpan.Attributes.Add("class", "C5LLC_input-left");
				}

				oInputDiv.Attributes.Add("class", "C5SLLC_input");

				//Setup for the Field Rule With the Event Caller
				//_ruleToFind = objFormControlInfo.ID
				fieldRule = (from s in _sourceFields where s.SourceField == objFormControlInfo.ID select s).FirstOrDefault();
				//fieldRule = _sourceFields.Find(AddressOf FindFieldRule)
				//_ruleToFind = String.Empty
				
				if (fieldRule != null)
				{
					strFieldOnEventText = "return fn" + objFormControlInfo.ID + "(this,\'";
					strFieldOnEventText += objFormControlInfo.Type.ToString() + "\',true); ";
					//strFieldOnEventText &= fieldRule.ContainsValue & "'); "
				}
				
				//If the User has used a Semi-Colon in the "Class" field, get that Class Name so
				//we can apply it to the TableCell
				string[] aryCssClass = objFormControlInfo.CssClass.Split(';');
				if (aryCssClass.Length == 2)
				{
					strControlClass = (string) (aryCssClass[0].Trim());
					strTdClass = (string) (aryCssClass[1].Trim());
				}
				else
				{
					strControlClass = objFormControlInfo.CssClass.Trim();
				}

				if (!objFormControlInfo.HideLabel && objFormControlInfo.Type != ControlType.HiddenField)
				{
					oLabelControl = (Label)(new Label());
					oLabelControl.ID = "lbl_" + objFormControlInfo.ID;
					oLabelControl.AssociatedControlID = objFormControlInfo.ID;
					oLabelControl.Width = Unit.Pixel(this._formSettings.LabelWidth);

					if (this._formInfo.CurrentPage.LabelPosition == 2)
					{
						oLabelControl.CssClass = String.Format("{0} C5LLC_label-left", objFormControlInfo.LabelCssClass);
					}
					else
					{
						oLabelControl.CssClass = String.Format("{0} C5LLC_control-label", objFormControlInfo.LabelCssClass);
					}

					if (objFormControlInfo.Type != ControlType.CheckBox)
					{
						oLabelControl.Text = objFormControlInfo.Label + (objFormControlInfo.Required ? objFormSettings.RequiredFieldSymbol : "").ToString();
					}
					else 
					{
						//oLabelControl.Text = "&#160;";
						oLabelControl.CssClass += " C5SLLC_cb-label";
						//oLabelControl.CssClass = String.Format("{0} C5SLLC_cb-label-left", objFormControlInfo.LabelCssClass);
					}

					if (objFormControlInfo.LabelAlign != HorizontalAlign.NotSet)
					{
						oLabelControl.CssClass += String.Format(" C5LLC_label-align-{0}", objFormControlInfo.LabelAlign.ToString().ToLower());
					}
					else if (objFormSettings.LabelAlign != HorizontalAlign.NotSet)
					{
						oLabelControl.CssClass += String.Format(" C5LLC_label-align-{0}", objFormSettings.LabelAlign.ToString().ToLower());
					}

					if (!String.IsNullOrWhiteSpace(labelStyle))
					{
						oLabelControl.Attributes.Add("style", labelStyle);
					}

					if (strTdClass != string.Empty)
					{
						oOutsideDiv.Attributes.Add("class", strTdClass);
					}

					controlDiv.Controls.Add(oLabelControl);
				}

				if (objFormControlInfo.ShowOnOwnRow)
				{
					if (oOutsideDiv.Attributes["style"] == null)
					{
						oOutsideDiv.Attributes.Add("style", "float:none;clear:both;");
					}
					else
					{
						oOutsideDiv.Attributes["style"] += "float:none;clear:both;";
					}
					oInputDiv.Attributes.Remove("class");
				}

				if (objFormControlInfo.Type == ControlType.FileUpload)
				{
					string strFileSizeFormatMsg = default(string);
					string strFileTypeFormatMsg = "";
					
					oLiteral = new Literal();
					if (!objFormControlInfo.HideMaxSize)
					{
						strFileSizeFormatMsg = Localization.GetString("FileSizeFormat.Text", this._sharedResourceFile);
						if (strFileSizeFormatMsg == string.Empty)
						{
							strFileSizeFormatMsg = "<br /><span class=\"Normal\"><strong>File Size:</strong> [MAXFILESIZE]KB Maximum<br /><strong></span>";
						}
						strFileSizeFormatMsg = strFileSizeFormatMsg.Replace("[MAXFILESIZE]", objFormControlInfo.MaxFileSize.ToString());
					}
					if (!objFormControlInfo.HideFileExtensions)
					{
						strFileTypeFormatMsg = Localization.GetString("FileTypeFormat.Text", this._sharedResourceFile);
						if (strFileTypeFormatMsg == string.Empty)
						{
							strFileTypeFormatMsg = "<br /><span class=\"Normal\"><strong>File Types:</strong> [FILETYPES]</span>";
						}
						strFileTypeFormatMsg = strFileTypeFormatMsg.Replace("[FILETYPES]", "." + objFormControlInfo.FileTypes.Replace(",", " ."));
					}
					
					oLiteral.Text = strFileSizeFormatMsg + strFileTypeFormatMsg;
					
					HtmlInputFile objHtmlControl = default(HtmlInputFile);
					objHtmlControl = new HtmlInputFile();
					objHtmlControl.ID = objFormControlInfo.ID;
					objHtmlControl.Disabled = !objFormControlInfo.Enabled;
					
					if (!HttpContext.Current.User.Identity.IsAuthenticated)
					{
						if (!objFormSettings.AllowAnonUploads)
						{
							objHtmlControl.Disabled = true;
						}
					}
					
					System.Int32 temp_result = objHtmlControl.Size;
					if (objFormControlInfo.Width.EndsWith("%"))
					{
						objHtmlControl.Attributes.Add("style", String.Format("width:{0};", objFormControlInfo.Width));
					}
					else if (int.TryParse(objFormControlInfo.Width, out temp_result))
					{
						objHtmlControl.Attributes.Add("style", String.Format("width:{0}px;", temp_result));
					}

					objHtmlControl.Attributes.Add("tabindex", objFormControlInfo.TabIndex);

					objHtmlControl.Attributes.Add("class", strControlClass);

					oInputDiv.Controls.Add(objHtmlControl);
					
					RegularExpressionValidator revFileType = new RegularExpressionValidator();
					revFileType.ID = "revType_" + objHtmlControl.ID;
					revFileType.CssClass = "NormalRed";
					revFileType.ForeColor = System.Drawing.Color.Empty;
					revFileType.ControlToValidate = objHtmlControl.ID;
					revFileType.ErrorMessage = "<br />" + Localization.GetString("FileFormat.ErrorMessage", this._sharedResourceFile);
					revFileType.Display = ValidatorDisplay.Dynamic;
					revFileType.EnableClientScript = true;
					
					
					string strExpression = string.Empty;
					string[] aryExt = objFormControlInfo.FileTypes.Split(',');
					for (int i = 0; i <= aryExt.Length - 1; i++)
					{
						strExpression += ".+\\." + aryExt[i].ToLower() + "$|";
						strExpression += ".+\\." + aryExt[i].ToUpper() + "$";
						if (i < aryExt.Length - 1)
						{
							strExpression += "|";
						}
					}
					
					revFileType.ValidationExpression = strExpression;
					
					revFileType.ValidationGroup = this.FormInfo.ValidationGroup;

					if (!String.IsNullOrWhiteSpace(oLiteral.Text))
					{
						oInputDiv.Controls.Add(oLiteral);
					}

					oInputDiv.Controls.Add(revFileType);
					
				}
				else if (objFormControlInfo.Type == ControlType.HTMLEditor)
				{
					string strCtl = "<%@ Register TagPrefix=\"dnn\" TagName=\"TextEditor\" Src=\"~/controls/TextEditor.ascx\"%>";
					strCtl += Environment.NewLine;
					strCtl += string.Format("<dnn:texteditor id=\"{0}\" width=\"{1}\" height=\"{2}\" runat=\"server\" />", objFormControlInfo.ID, objFormControlInfo.Width, objFormControlInfo.Height);
					Control htmlEditor = phForm.Page.ParseControl(strCtl);
					oInputDiv.Controls.Add(htmlEditor);
					
				}
				else if (objFormControlInfo.Type == ControlType.HiddenField)
				{
					HtmlInputHidden oHiddenField = new HtmlInputHidden();

					if (objFormControlInfo.FieldName.ToLower() == "datarecordid")
					{
						oHiddenField.ID = objFormControlInfo.FieldName.ToLower();
					}
					else
					{
						oHiddenField.ID = objFormControlInfo.ID;
					}

					oHiddenField.Attributes.Add("class", objFormControlInfo.CssClass);

					oHiddenField.Attributes.Add("data-id", objFormControlInfo.CalcId);

					oHiddenField.Value = GetAutoFillValue(objFormControlInfo);

					if (!String.IsNullOrWhiteSpace(objFormControlInfo.Formula))
					{
						oHiddenField.Attributes.Add("data-formula", objFormControlInfo.Formula);
						this.HasCalculation = true;
					}

					phForm.Controls.Add(oHiddenField);
				}
				else
				{
					oInputControl = (WebControl) (GetFormControl(objFormControlInfo));

					oInputControl.Enabled = objFormControlInfo.Enabled;
					oInputControl.CssClass = strControlClass;
					oInputControl.Width = Unit.Empty;

					if (!String.IsNullOrWhiteSpace(objFormControlInfo.Width))
					{
						if (objFormControlInfo.Width.EndsWith("%"))
						{
							oInputControl.Width = Unit.Percentage(double.Parse(objFormControlInfo.Width.Replace("%", "")));
						}
						else
						{
							oInputControl.Width = Unit.Pixel(int.Parse(objFormControlInfo.Width));
						}
					}
					
					if (objFormControlInfo.Height != string.Empty)
					{
						oInputControl.Height = System.Web.UI.WebControls.Unit.Pixel(int.Parse(objFormControlInfo.Height));
					}
					
					switch (objFormControlInfo.Type)
					{
						
					case ControlType.Label:
						if (oInputControl.Width.IsEmpty)
						{
							oInputControl.Width = Unit.Percentage(100.0);
						}
						break;
						//oInputControl.TabIndex = -1
						
					case ControlType.CheckBox:
						C5CheckBox cBox = oInputControl as C5CheckBox;
						cBox.LabelCssClass = objFormControlInfo.LabelCssClass;
						oOutsideDiv.Attributes.Add("class", "C5LLC_chkbx-cell");
						cBox.Checked = objFormControlInfo.Checked;
						cBox.TabIndex = short.Parse(objFormControlInfo.TabIndex);
						cBox.Attributes.Add("style", "display:inline-block");
						cBox.CssClass = objFormControlInfo.CssClass;
						if (objFormControlInfo.HideLabel == false)
						{
							cBox.Text = objFormControlInfo.Label;
							cBox.CssClass += " " + objFormControlInfo.LabelCssClass;
						}
						
						if (!string.IsNullOrEmpty(strFieldOnEventText))
						{
							cBox.Attributes.Add("onclick", strFieldOnEventText);
						}

						bool isChecked = default(bool);
						string value = GetAutoFillValue(objFormControlInfo);
						if (!bool.TryParse(value, out isChecked))
						{
							if (String.IsNullOrWhiteSpace(value))
								value = "C5SLLC";
							cBox.Value = value;
						}
						else
						{
							if (!cBox.Checked)
							{
								cBox.Checked = isChecked;
							}
						}

						cBox.Attributes.Add("data-id", objFormControlInfo.CalcId);
						oInputControl = cBox;
						break;
						
						
					case ControlType.CheckBoxList:
						C5CheckBoxList chkCheckBoxList = (C5CheckBoxList)oInputControl;
						chkCheckBoxList.LabelCssClass = objFormControlInfo.LabelCssClass;
						chkCheckBoxList.TabIndex = short.Parse(objFormControlInfo.TabIndex);
						chkCheckBoxList.RepeatColumns = int.Parse(objFormControlInfo.RepeatColumns);
						chkCheckBoxList.RepeatDirection = objFormControlInfo.RepeatDirection;
						chkCheckBoxList.CellPadding = 0;
						chkCheckBoxList.CellSpacing = 0;
						chkCheckBoxList.BorderStyle = BorderStyle.None;
						chkCheckBoxList.RepeatLayout = RepeatLayout.Flow;
						ListItem lItem;
						
						if (objFormControlInfo.FillListItemText != string.Empty)
						{
							FillControlFromQuery(chkCheckBoxList, objFormControlInfo);
						}

						if (objFormControlInfo.AutoFillType != AutoFillType.None)
						{
							string strAutoValue = GetAutoFillValue(objFormControlInfo);

							foreach (var selectedValue in strAutoValue.FromCSV())
							{
								if (objFormControlInfo.ListItemToSave == ListItemToSave.Text)
								{
									lItem = chkCheckBoxList.Items.FindByText(selectedValue);
								}
								else
								{
									lItem = chkCheckBoxList.Items.FindByValue(selectedValue);
								}

								if (lItem != null)
								{
									lItem.Selected = true;
								}
							}
						}
						
						if (!string.IsNullOrEmpty(strFieldOnEventText))
						{
							chkCheckBoxList.Attributes.Add("onclick", strFieldOnEventText);
						}
						oInputControl.Attributes.Add("data-id", objFormControlInfo.CalcId);
						break;
						
					case ControlType.RadioButtonList:
						C5RadioButtonList rdoRadioButtonList = (C5RadioButtonList)oInputControl;
						rdoRadioButtonList.LabelCssClass = objFormControlInfo.LabelCssClass;
						rdoRadioButtonList.TabIndex = short.Parse(objFormControlInfo.TabIndex);
						rdoRadioButtonList.RepeatColumns = int.Parse(objFormControlInfo.RepeatColumns);
						rdoRadioButtonList.RepeatDirection = objFormControlInfo.RepeatDirection;
						rdoRadioButtonList.CellPadding = 0;
						rdoRadioButtonList.CellSpacing = 0;
						rdoRadioButtonList.BorderStyle = BorderStyle.None;
						rdoRadioButtonList.RepeatLayout = RepeatLayout.Flow;
						
						if (objFormControlInfo.FillListItemText != string.Empty)
						{
							FillControlFromQuery(rdoRadioButtonList, objFormControlInfo);
						}
						
						if (objFormControlInfo.AutoFillType != AutoFillType.None)
						{
							string strAutoValue = GetAutoFillValue(objFormControlInfo);
							rdoRadioButtonList.SelectedIndex = rdoRadioButtonList.Items.IndexOf(rdoRadioButtonList.Items.FindByText(strAutoValue));
						}
						
						if (!string.IsNullOrEmpty(strFieldOnEventText))
						{
							rdoRadioButtonList.Attributes.Add("onclick", strFieldOnEventText);
						}
						oInputControl.Attributes.Add("data-id", objFormControlInfo.CalcId);
						break;
						
						
					case ControlType.TextBox:
						if (objFormControlInfo.UseCalendar)
						{
							//oOutsideDiv.Attributes["class"] += " dtpickerfix";
							C5DatePicker picker = new C5DatePicker();
							picker.ID = objFormControlInfo.ID;
							picker.MinDate = DateTime.Now.AddYears(-80);
							DateTime autoFilldate;
							if (DateTime.TryParse(GetAutoFillValue(objFormControlInfo), out autoFilldate))
							{
								picker.SelectedDate = autoFilldate;
							}
							picker.CssClass = objFormControlInfo.CssClass;
							if (!String.IsNullOrWhiteSpace(objFormControlInfo.Width))
							{
								int width;
								if (int.TryParse(objFormControlInfo.Width, out width))
								{
									picker.Width = Unit.Pixel(width);
								}
							}

							if (!String.IsNullOrWhiteSpace(objFormControlInfo.Height))
							{
								int height;
								if (int.TryParse(objFormControlInfo.Height, out height))
								{
									picker.Height = Unit.Pixel(height);
								}
							}

							picker.Attributes.Add("type", "date");

							if (!String.IsNullOrWhiteSpace(objFormControlInfo.Placeholder))
							{
								picker.Attributes.Add("placeholder", objFormControlInfo.Placeholder);
							}

							oInputControl = picker;
						}
						else
						{
							((TextBox)oInputControl).Text = GetAutoFillValue(objFormControlInfo);
							if (objFormControlInfo.Columns != string.Empty)
							{
								((TextBox)oInputControl).Columns = int.Parse(objFormControlInfo.Columns);
							}
							if (objFormControlInfo.TextMode == TextBoxMode.MultiLine)
							{
								((TextBox)oInputControl).Wrap = objFormControlInfo.WrapHard;

								if (objFormControlInfo.Rows != string.Empty)
								{
									((TextBox)oInputControl).Rows = int.Parse(objFormControlInfo.Rows);
								}
							}

							if (!String.IsNullOrWhiteSpace(objFormControlInfo.Placeholder))
							{
								oInputControl.Attributes.Add("placeholder", objFormControlInfo.Placeholder);
							}

							oInputControl.Attributes.Add("data-id", objFormControlInfo.CalcId);
						}

						oInputControl.TabIndex = short.Parse(objFormControlInfo.TabIndex);

						if (!string.IsNullOrEmpty(strFieldOnEventText))
						{
							oInputControl.Attributes.Add("onblur", strFieldOnEventText);
						}

						if (!String.IsNullOrWhiteSpace(objFormControlInfo.Formula))
						{
							oInputControl.Attributes.Add("data-formula", objFormControlInfo.Formula);
							this.HasCalculation = true;
						}
						
						break;
						
					case ControlType.ListBox:
						oInputControl.TabIndex = short.Parse(objFormControlInfo.TabIndex);
						ListBox lstListBox = (ListBox) oInputControl;
						lstListBox.SelectionMode = objFormControlInfo.SelectionMode;
						
						if (objFormControlInfo.FillListItemText != string.Empty)
						{
							FillControlFromQuery(lstListBox, objFormControlInfo);
						}
						
						if (objFormControlInfo.AutoFillType != AutoFillType.None)
						{
							string strAutoValue = GetAutoFillValue(objFormControlInfo);
							lstListBox.SelectedIndex = lstListBox.Items.IndexOf(lstListBox.Items.FindByText(strAutoValue));
						}
						
						oLiteral = new Literal();
						oLiteral.Text = Localization.GetString("MultiSelect.Text", Utility.GetSharedResourceFile());
						
						if (!string.IsNullOrEmpty(strFieldOnEventText))
						{
							lstListBox.Attributes.Add("onchange", strFieldOnEventText);
						}
						oInputControl.Attributes.Add("data-id", objFormControlInfo.CalcId);
						break;
						
					case ControlType.DropDownList:
						oInputControl.TabIndex = short.Parse(objFormControlInfo.TabIndex);
						DropDownList lstDropDown = (DropDownList) oInputControl;
						
						if (objFormControlInfo.FillListItemText != string.Empty)
						{
							FillControlFromQuery(lstDropDown, objFormControlInfo);
						}
						
						if (objFormControlInfo.AutoFillType != AutoFillType.None)
						{
							string strAutoValue = GetAutoFillValue(objFormControlInfo);
							if (objFormControlInfo.ListItemToSave == ListItemToSave.Text)
							{
								lstDropDown.SelectedIndex = lstDropDown.Items.IndexOf(lstDropDown.Items.FindByText(strAutoValue));
							}
							else
							{
								lstDropDown.SelectedIndex = lstDropDown.Items.IndexOf(lstDropDown.Items.FindByValue(strAutoValue));
							}
							
						}
						
						if (!string.IsNullOrEmpty(strFieldOnEventText))
						{
							lstDropDown.Attributes.Add("onchange", strFieldOnEventText);
						}
						oInputControl.Attributes.Add("data-id", objFormControlInfo.CalcId);
						break;
						
					case ControlType.SubmitButton:
						oInputControl.TabIndex = short.Parse(objFormControlInfo.TabIndex);
						switch (objFormControlInfo.ButtonType)
						{
							case Code5Systems.FormMaster.Business.ButtonType.Button:
								((Button) oInputControl).Text = objFormControlInfo.Label;
								((Button)oInputControl).ValidationGroup = this.FormInfo.ValidationGroup;
								break;

							case Code5Systems.FormMaster.Business.ButtonType.LinkButton:
								((LinkButton) oInputControl).Text = objFormControlInfo.Label;
								((LinkButton)oInputControl).ValidationGroup = this.FormInfo.ValidationGroup;
								break;

							case Code5Systems.FormMaster.Business.ButtonType.ImageButton:
								PortalSettings _portalSettings = DotNetNuke.Entities.Portals.PortalController.GetCurrentPortalSettings();
							
								int intVal;
								int.TryParse(objFormControlInfo.ButtonImage, out intVal);
								DotNetNuke.Services.FileSystem.FileInfo oFileInfo = FileManager.Instance.GetFile(intVal) as DotNetNuke.Services.FileSystem.FileInfo;
								
								if (oFileInfo != null)
								{
									((ImageButton) oInputControl).ImageUrl = _portalSettings.HomeDirectory + oFileInfo.Folder + oFileInfo.FileName;
								}
								
								((ImageButton) oInputControl).AlternateText = objFormControlInfo.Label;

								((ImageButton)oInputControl).ValidationGroup = this.FormInfo.ValidationGroup;
								break;
								
						}
						this.FormButtons.Add(oInputControl);
						break;
					}
				
					oInputDiv.Controls.Add(oInputControl);

					if (oLiteral != null)
					{
						oOutsideDiv.Controls.Add(oLiteral);
					}
				}
			
				//If the Control is a Target of any Field Rules, add it to the collection for later processing
				if (_targetFields.Contains(objFormControlInfo.ID))
				{
				
					foreach (FieldRulesScriptInfo tempLoopVar_oFieldRulesScriptInfo in sInfos)
					{
						oFieldRulesScriptInfo = tempLoopVar_oFieldRulesScriptInfo;
						if (oFieldRulesScriptInfo != null)
						{
							//Add the FormControlInfo for the Target Field
							oFieldRulesScriptInfo.TargetControlInfos.Add(objFormControlInfo.ID, objFormControlInfo);
						
							//Add the Panel Control for the Target Field
							oFieldRulesScriptInfo.TargetControls.Add(objFormControlInfo.ID, oOutsideDiv);
						
							//Add the Label Control for the Target Field
							if (oLabelControl != null)
							{
								oFieldRulesScriptInfo.TargetLabels.Add(oLabelControl);
							}
						
						}
					}
				
					//Get the Source Field for this Target Fiels
					FormFieldRulesInfo sourceField = GetSourceFieldByTarget(objFormControlInfo.ID);
				
					if (sourceField != null)
					{
						string fillValue = GetAutoFillValue(objFormControlInfo);
					
						FormControlInfo sourceCtlInfo = this.GetFormControlInfo(sourceField.SourceField);
					
						if (sourceCtlInfo != null)
						{
						
							switch (sourceCtlInfo.Type)
							{
								case ControlType.CheckBox:
									if (sourceCtlInfo.Checked)
									{
										fillValue = "Checked";
									}
									break;
								case ControlType.RadioButtonList:
									RadioButtonList rdoCtrl = (RadioButtonList) (GetFormControl(sourceCtlInfo));
									fillValue = GetAutoFillValue(sourceCtlInfo);
									if (string.IsNullOrEmpty(fillValue))
									{
										fillValue = rdoCtrl.SelectedValue;
									}
									break;
								case ControlType.DropDownList:
									DropDownList lstCtl_1 = (DropDownList) (GetFormControl(sourceCtlInfo));
									fillValue = GetAutoFillValue(sourceCtlInfo);
									if (string.IsNullOrEmpty(fillValue))
									{
										fillValue = lstCtl_1.SelectedValue;
									}
									break;
								case ControlType.ListBox:
									ListBox lstCtl = (ListBox) (GetFormControl(sourceCtlInfo));
									foreach (ListItem item in lstCtl.Items)
									{
										if (item.Selected)
										{
											fillValue += item.Value + ",";
										}
									}
									break;
								case ControlType.CheckBoxList:
									fillValue = string.Empty;
									CheckBoxList chkLst = (CheckBoxList) (GetFormControl(sourceCtlInfo));
									foreach (ListItem item in chkLst.Items)
									{
										if (item.Selected)
										{
											fillValue += item.Value + ",";
										}
									}
									break;
								default:
									fillValue = GetAutoFillValue(sourceCtlInfo);
									break;
							}
						}
					
						string strDisplay = string.Empty;
					
						if (sourceField.ContainsValue == "*.*")
						{
							if (!string.IsNullOrEmpty(fillValue))
							{
								strDisplay = "display:block;";
								enableValidators = true;
							}
							else
							{
								strDisplay = "display:none;";
								enableValidators = false;
							}
							if(oOutsideDiv.Attributes["style"] == null)
								oOutsideDiv.Attributes.Add("style", strDisplay);
							else
								oOutsideDiv.Attributes["style"] += strDisplay;

							if (oLabelControl != null)
							{
								oLabelControl.Attributes.Add("style", strDisplay);
							}
						}
						else if (!fillValue.Contains(sourceField.ContainsValue))
						{
							if (oOutsideDiv.Attributes["style"] == null)
								oOutsideDiv.Attributes.Add("style", "display:none;");
							else
								oOutsideDiv.Attributes["style"] += "display:none;";

							if (oLabelControl != null)
							{
								oLabelControl.Attributes.Add("style", "display:none;");
							}
							enableValidators = false;
						}
					
					}
				}
			
				if (strTdClass != string.Empty)
				{
					controlDiv.Attributes.Add("class", strTdClass);
				}
			
				if (objFormControlInfo.Validators.Count > 0)
				{
					this.HasValidators = true;
					System.Collections.IEnumerator myEnumerator = objFormControlInfo.Validators.GetEnumerator();
					while (myEnumerator.MoveNext())
					{
					
						objValidatorFormControlInfo = (FormControlInfo) myEnumerator.Current;
					
						oValidatorControl = (BaseValidator) (GetFormControl(objValidatorFormControlInfo));

						oValidatorControl.Attributes.Add("data-c5val", "0");
					
						oValidatorControl.EnableClientScript = objFormSettings.EnableClientScript;

						oValidatorControl.ValidationGroup = this.FormInfo.ValidationGroup;
					
						oValidatorControl.Enabled = enableValidators;
					
						oValidatorControl.SetFocusOnError = objValidatorFormControlInfo.SetFocusOnError;

						oInputValSpan.Attributes.Add("class", "C5LLC_val-left");
					
						if (!oValidatorControl.Enabled)
						{
							if (!_disabledValidators.Contains(oValidatorControl))
							{
								_disabledValidators.Add(oValidatorControl);
							}
						}

						if (objFormSettings.SupressFieldValidationMessages)
						{
							oInputDiv.Controls.Add(oValidatorControl);
						}
						else
						{
							oInputValSpan.Controls.Add(oValidatorControl);

							if (objFormSettings.UseFormErrorFormatting)
							{
								oInputDiv.Controls.AddAt(0, oInputValSpan);
							}
							else
							{
								oInputDiv.Controls.Add(oInputValSpan);
							}
						}
					
						if (objValidatorFormControlInfo.Type == ControlType.RequiredFieldValidator)
						{
							_hasRequredFieldValidators = true;
						}
					
						foreach (FieldRulesScriptInfo tempLoopVar_oFieldRulesScriptInfo in sInfos)
						{
							oFieldRulesScriptInfo = tempLoopVar_oFieldRulesScriptInfo;
							oFieldRulesScriptInfo.TargetValidators.Add(oValidatorControl);
						}
					}
				}
			}

			controlDiv.Controls.Add(oInputDiv);
			oOutsideDiv.Controls.Add(controlDiv);

			return oOutsideDiv;
		
		}
	
		private void AddCaptchaRwd(FormInfo oFormInfo, Table oTable)
		{
			TableRow oRow = new TableRow();
			oRow.ID = "trCaptchaRow_" + oFormInfo.ModuleID.ToString();
			oRow.Visible = true;
		
			TableCell oControlCell = new TableCell();
			oControlCell.ID = "tdCapthcaCell_" + oFormInfo.ModuleID.ToString();
			oControlCell.ColumnSpan = System.Convert.ToInt32(oFormInfo.CurrentPage.LabelPosition == 2 ? oFormInfo.TableColumns * 2 : oFormInfo.TableColumns);
			oControlCell.HorizontalAlign = HorizontalAlign.Center;
			oControlCell.Attributes.Add("style", "padding:5px;");
		
			CaptchaControl ctlCaptcha = new CaptchaControl();
			ctlCaptcha.ID = "cpt_FormMaster_" + oFormInfo.ModuleID.ToString();
			ctlCaptcha.TabIndex = (short) (GetControlCount(oFormInfo) + 1);
			ctlCaptcha.CaptchaWidth = Unit.Pixel(130);
			ctlCaptcha.CaptchaChars = System.Convert.ToString((oFormInfo.CaptchaCharacters == string.Empty ? (Localization.GetString("CaptchaCharaters", this.SharedResouceFile)) : oFormInfo.CaptchaCharacters).ToString());
			ctlCaptcha.CaptchaHeight = Unit.Pixel(40);
			ctlCaptcha.Text = Localization.GetString("CaptchaText", this.SharedResouceFile);
			ctlCaptcha.CssClass = "Normal";
			ctlCaptcha.ErrorStyle.CssClass = "NormalRed";
			ctlCaptcha.ErrorMessage = Localization.GetString("CaptchaErrorMsg", Utility.GetSharedResourceFile());
		
			oControlCell.Controls.Add(ctlCaptcha);
			oRow.Cells.Add(oControlCell);
			oTable.Rows.Add(oRow);
		}
	
}

}

